<template>
    <div style="height: 100px; width: 300px">
        <video
            id="myVideo"
            class="video-js vjs-default-skin vjs-big-play-centered"
            controls
            preload="auto"
            v-show="true"
        ></video>
        <button @click="startPlay" v-if="playState === 'suspended'">播放</button>

        <canvas id="canvas" style="width: 100%;height: 100%;"></canvas>
    </div>
</template>

<script>
import videojs from 'video.js'
import 'video.js/dist/video-js.css'
import 'videojs-contrib-hls'

export default {
    name: 'AudioVisual',
    components: {},
    props: {
        audioSrc: {
            type: String,
            // default: 'http://192.168.0.39:20000/channelau64.m3u8',
            default: 'http://192.168.0.39:20000/channelau44.m3u8'
            // default: 'http://192.168.0.39:20000/channel44.m3u8'
        }
    },
    data() {
        return {
            playerEl: null,
            myVideo: null,
            audioContext: '', // 音频实例
            playState: 'suspended' // 默认是未播放状态
        }
    },
    watch: {
      audioSrc(newVal, oldVal) {



      }
    },
    mounted() {
        this.getVideo()
    },
    methods: {
        startPlay(){
            this.myVideo.play()
           // this.createCanvas()

        },
        createCanvas() {
            let playerEl = document.getElementById('myVideo').getElementsByTagName('video')[0]
            this.playerEl = playerEl
            let canvas = document.getElementById('canvas')
            let AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext;

            this.audioContext = new AudioContext();//实例化
            let canvasCtx = canvas.getContext("2d");

            let audioBufferSourceNode = this.audioContext.createMediaElementSource(playerEl)

            let analyser = this.audioContext.createAnalyser();
            analyser.fftSize = 128;
            audioBufferSourceNode.connect(analyser);
            analyser.connect(this.audioContext.destination);
            // 播放
            this.audioContext.resume().then(()=>{
                this.playState = this.audioContext.state
            })

            let bufferLength = analyser.frequencyBinCount;
            let dataArray = new Uint8Array(bufferLength);

            let oW = canvas.width;
            let oH = canvas.height;
            let color1 = canvasCtx.createLinearGradient(oW / 2, oH / 2 - 10, oW / 2, oH / 2 - 150);
            let color2 = canvasCtx.createLinearGradient(oW / 2, oH / 2 + 10, oW / 2, oH / 2 + 150);
            color1.addColorStop(0, '#1E90FF');
            color1.addColorStop(.25, '#FF7F50');
            color1.addColorStop(.5, '#8A2BE2');
            color1.addColorStop(.75, '#4169E1');
            color1.addColorStop(1, '#00FFFF');

            color2.addColorStop(0, '#1E90FF');
            color2.addColorStop(.25, '#FFD700');
            color2.addColorStop(.5, '#8A2BE2');
            color2.addColorStop(.75, '#4169E1');
            color2.addColorStop(1, '#FF0000');

            function draw() {
                let drawVisual = requestAnimationFrame(draw);
                let barHeight;
                // 自定义获取数组里边数据的频步
                canvasCtx.clearRect(0, 0, oW, oH);
                for (let i = 0; i < bufferLength; i++) {
                    barHeight = dataArray[i] / 4;
                    analyser.getByteFrequencyData(dataArray);
                    // 绘制向上的线条
                    canvasCtx.fillStyle = color1;
                    /* context.fillRect(x,y,width,height)
                     * x，y是坐标
                     * width，height线条的宽高
                     */
                    canvasCtx.fillRect(oW / 2 + (i * 8), oH / 2, 2, -barHeight);
                    canvasCtx.fillRect(oW / 2 - (i * 8), oH / 2, 2, -barHeight);
                    // 绘制向下的线条
                    canvasCtx.fillStyle = color2;
                    canvasCtx.fillRect(oW / 2 + (i * 8), oH / 2, 2, barHeight);
                    canvasCtx.fillRect(oW / 2 - (i * 8), oH / 2, 2, barHeight);
                }
            };
            draw();

            // playerEl.addEventListener('paste', () => {
            //     // 暂停
            //     this.audioContext.suspend()
            //
            //     //释放audioContext的所有资源
            //     // this.audioContext.close();
            // })
        },
        getVideo() {
            this.myVideo = videojs(
                'myVideo',
                {
                    autoplay: true, // 自动播放
                    // loop: true, // 循环播放
                    controls: true, // 控制元件
                    // width: 500, // 视频播放器显示的宽度
                    // height: 300, // 视频播放器显示的高度
                    preload: 'none',
                    bigPlayButton: true,
                    posterImage: false,
                    textTrackDisplay: false,
                    errorDisplay: false,
                    controlBar: true,
                    sources: [{
                        src: this.audioSrc,
                        type: 'application/x-mpegURL'
                    }]
                },
                () => {
                    this.myVideo.on('play', ()=>{
                        console.log('视频播放')
                        if(this.audioContext){
                            // 播放
                            this.audioContext.resume().then(()=>{
                                this.playState = this.audioContext.state
                            })
                        }else {
                            this.createCanvas()
                        }
                    })
                    this.myVideo.on("pause", ()=>{
                        console.log("视频暂停播放")
                        this.audioContext.suspend().then(()=>{
                            this.playState = this.audioContext.state
                        })
                    });
                }
            )

        }
    }
}
</script>
